<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>

        const arr = Array.from({ length: 10000 }, (v, i) => i);

        const render = (item, index) => {
            const body = document.body;
            const div = document.createElement('div');
            div.innerText = item;
            body.appendChild(div);
        }

        // const scheduler = (fn) => {
        //     setTimeout(() => {
        //         fn(() => {
        //             return 11;
        //         });
        //     }, 1000);
        // }

        // const scheduler = (fn) => {
        //     // 50ms执行一次
        //     setTimeout(() => {
        //         let start = performance.now();
        //         fn(() => {
        //             return performance.now() - start < 50;
        //         });
        //     }, 1000);
        // }

        const scheduler = (fn) => {
            // 空闲时间执行
            requestIdleCallback((deadline) => {
                fn(() => deadline.timeRemaining() > 1)
            })
        }

        // 1. 何时执行
        // 2. 每次执行多久
        function wookloop(datas, tashHander, scheduler) {
            // 参数归一化，支持数字
            if (typeof datas === 'number') {
                // datas = { length: datas };
                datas = Array.from({ length: datas }, (v, i) => i);
            }

            if (!datas.length) return;
            let index = 0;

            function loop(isCanRun) {
                // 由isCanRun决定是否继续执行
                while (index < datas.length && isCanRun()) {
                    tashHander(datas[index], index);
                    index++;
                }
                if (index < datas.length) {
                    scheduler(loop);
                }
            }
            // 调度器
            scheduler(loop);
        }

        // wookloop(arr, render, scheduler);
        wookloop(10000, render, scheduler);
    </script>
</body>

</html>
</script>
</body>

</html>